<?php

namespace app\data\controller\control;
use app\data\model\ControlPlanListModel;
use app\data\model\ControlPlanModel;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\facade\Db;

/**
 * 计划管理
 * Class Cate
 * @package app\data\controller\shop
 */
class Plan extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SnControlPlan';

    /**
     * 计划管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = "计划管理";
        // 加载对应数据
        $query = $this->_query($this->table);
        $this->type = $this->request->get('type', 'index');
        if ($this->type === 'index') $query->where(['deleted' => 0]);
        elseif ($this->type === 'recycle') $query->where(['deleted' => 1]);
        else $this->error("无法加载 $this->type 数据列表！");
        $query->equal('status,admin_id,cate_id')->like('id,plan_title');
        $userInfo = session('user');
        if($userInfo['id'] == 10000){
            $where = array();
        }elseif($userInfo['authorize'] == 7){
            //保管员
            $where = array();
        }else{
            $where = array('admin_id'=>$userInfo['id']);
        }
        $query->where($where)->order('id desc')->page();
    }


    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as $k=>$v){
            $data[$k]['merge_time'] = Db::name('sn_control_plan_merge')->where('id',$v['merge_id'])->value('merge_time');
            $data[$k]['keshi_name'] = Db::name('system_user')->where('id',$v['keshi_id'])->value('username');
        }
        $this->userlist = Db::name('system_user')->where('authorize','1')->field('id,username,nickname')->select()->toArray();
    }


    /**
     * 添加
     * @auth true
     */
    public function add()
    {
        $this->mode = 'add';
        $this->title = '添加计划数据';
        $this->_form($this->table, 'add');
    }

    /**
     * 编辑
     * @auth true
     */
    public function edit()
    {
        $this->mode = 'edit';
        $this->title = '编辑计划数据';
        $this->_form($this->table, 'edit');
    }

    
    /**
     * 复制
     * @auth true
     */
    public function copy()
    {
        $this->mode = 'copy';
        $this->title = '复制计划';
        $this->_form($this->table, 'copy');
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        $userInfo = session('user');
        if ($this->request->isGet()) {
            if(isset($data['id'])){
                $this->lists = ControlPlanListModel::where('plan_id',$data['id'])->select()->toArray();
            }
            $where['is_deleted'] = 0;
            if($userInfo['id'] == 10000){
                $this->keshi_list = [];
            }else{
                $this->keshi_list = Db::name('system_user')->where('authorize',$userInfo['authorize']+1)->where($where)->field('id,nickname,username')->select()->toArray();
            }
        } elseif ($this->request->isPost()){
            if(!isset($data['material_code']) || count($data['material_code'])==0){$this->error('材料列表不可为空');}
            if(!isset($data['plan_type'])){$this->error('计划类型不可为空');}
            if(!isset($data['keshi_id'])){$this->error('下级审批人不可为空');}
            foreach ($data['material_num'] as $ks => $vs){
                if(!$vs){$this->error($data['material_name'][$ks].'('.$data['material_code'][$ks].')'.'数量不可为0');}
            }
            if(isset($data['copy_status']) and $data['copy_status']){
                unset($data['id']);
            }
            // dump($data);die;
            if(!isset($data['id'])){
                //添加
                //获取标题
                if($data['plan_type']){
                    //获取计划时间
                    $yuefen = date('m',time())+1;
                    if($yuefen>12){
                        $nian = date('Y',time())+1;
                        $yuefen = 1;
                    }else{
                        $nian = date('Y',time());
                    }
                    $title = $nian.'年'.$yuefen.'月（月度计划）';
                    $data['plan_data_status'] = date('Ym',time())+1;
                    //判断当月计划是否有提交过
//                    $wheres = array(
//                        'plan_data_status'=>$nian.$yuefen,
//                        'admin_id'=>$userInfo['id'],
//                        'plan_type'=>1,
//                    );
                    // $isSubmit = ControlPlanModel::where($wheres)->value('status');
                    // if($isSubmit && $isSubmit != -1){
                    //     $this->error($nian.'年'.$yuefen .'月计划已提交，不可重复提交');
                    // }


                }else{
                    //获取计划时间
                    $yuefen = date('m',time());
                    if($yuefen>12){
                        $nian = date('Y',time())+1;
                        $yuefen = 1;
                    }else{
                        $nian = date('Y',time());
                    }
                    $title = $nian.'年'.$yuefen.'月（临时计划）';
                    $data['plan_data_status'] = date('Ym',time());
                    //判断当月临时计划是否已限制提交
//                    $wheres = array(
//                        'plan_data_status'=>$nian.$yuefen,
//                        'admin_id'=>$userInfo['id'],
//                        'plan_type'=>0,
//                    );
                    // $isSubmitCount = PlanApplyModel::where($wheres)->count();
                    // if($isSubmitCount > 2){
                    //     $this->error($nian.'年'.$yuefen .'当月临时计划提交次数已上限');
                    // }
                }

                $data['plan_title'] = $title;
                // 生成计划ID
                $data['id'] = CodeExtend::uniqidNumber(10,'J');
            }
            $data['admin_id'] = $userInfo['id'];
            $data['admin_name'] = $userInfo['username'];
            $cate_list = array();
            //组合数组
            foreach ($data['material_code'] as $k=>$v){
                $cate_list[$k]['material_code'] = $v;
                $cate_list[$k]['material_name'] = $data['material_name'][$k];
                $cate_list[$k]['material_model'] = $data['material_model'][$k];
                $cate_list[$k]['material_unit'] = $data['material_unit'][$k];
                $cate_list[$k]['material_price'] = $data['material_price'][$k];
                $cate_list[$k]['material_num'] = $data['material_num'][$k];
                $cate_list[$k]['material_xjprice'] = sprintf("%01.2f", $data['material_price'][$k] * $data['material_num'][$k]);
                $cate_list[$k]['material_notes'] = $data['material_notes'][$k];
                $cate_list[$k]['plan_id'] = $data['id'];
                $cate_list[$k]['admin_id'] = $data['admin_id'];
                $cate_list[$k]['admin_name'] = $data['admin_name'];
                $cate_list[$k]['plan_time'] = date('Y-m-d H:i:s',time());
                $cate_list[$k]['cate_id'] = $data['cate_id'];
            }
            //获取提交时间
            $data['plan_time'] = time();
            $data['status'] = 0;
            //开启事务
            Db::startTrans();
            try{
                //删除计划流程数据
                $time_del = Db::name('sn_control_plan_time')->where('collect_id',$data['id'])->delete();
                if ($time_del === false) {throw new \Exception("服务器错误");}
                //如果发起人为业务科室
                if($userInfo['authorize'] >1){
                    //添加一条合并数据
                    $iet_arr = array(
                        'title' => date('Y年m月d日',time()).'业务科室计划',
                        'plan_ids'=>$data['id'],
                        'admin_id'=>$userInfo['id'],
                        'admin_name'=>$userInfo['username'],
                        'merge_time'=>date('Y-m-d H:i:s',time()),
                        'admin_nickname'=>$userInfo['nickname'],
                        'plan_status'=>3,
                        'below_admin_id'=>$data['keshi_id']
                    );
                    $data['merge_id'] = Db::name('sn_control_plan_merge')->insertGetId($iet_arr);
                }

                //删除计划子表数据
                $listDel = Db::name('sn_control_plan_list')->where('plan_id',$data['id'])->delete();
                if ($listDel === false) {throw new \Exception("服务器错误");}
                // 子表数据添加
                $applyAll = Db::name('sn_control_plan_list')->insertAll($cate_list);
               if (!$applyAll) {throw new \Exception("服务器错误");}
                // 执行提交操作
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
        }
    }


    /**
     * 查看流程
     * @auth true
     */
    public function ca_detail()
    {
        $plan_list = Db::name('sn_control_plan_time')->where('collect_id',input('id'))->order('admin_authorize asc')->select()->toArray();
        $this->assign('shlist',$plan_list);
        $plan_status = ControlPlanModel::where('id',input('id'))->find();
        $this->assign('info',$plan_status);
        $this->fetch();
    }
    /**
     * 表单结果处理
     * @param boolean $result
     */
    protected function _form_result($result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('数据更新成功！');
        }
    }


    /**
     * 详情
     * @auth true
     */
    public function detail()
    {
        $this->title = '详情';
        $data = input('get.');
        $where = array(
            'deleted'=>0,
            'id'=>$data['id']
        );
        $info = ControlPlanModel::where($where)->order('id desc')->find();
        $this->assign('info',$info);
        $plan_list = ControlPlanListModel::where('plan_id',$where['id'])->order('material_code asc')->select()->toArray();
        $this->assign('plan_list',$plan_list);
        $total = 0;
        if($plan_list){
            foreach ($plan_list as $v){
                $total += $v['material_price'] * $v['material_num'];
            }
        }else{
            $plan_list = [];
        }

        $this->assign('plan_list',$plan_list);
        $this->assign('total',$total);
        $this->fetch();
    }


    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        $this->_save($this->table, $this->_vali([
            'deleted.in:0,1'  => '状态值范围异常！',
            'deleted.require' => '状态值不能为空！',
        ]), 'id');
    }
}